//
//  TTAccountService.m
//  TTBaseProject
//
//  Created by shny588 on 16/7/20.
//  Copyright © 2016年 tt. All rights reserved.
//

#import "TTAccountService.h"

static NSString * const AccountUserIdKey = @"AccountUserIdDefaultsKey";

@implementation TTAccountService

+ (TTAccountService *)shared {
    static dispatch_once_t pred;
    static TTAccountService *sharedInstance = nil;
    
    dispatch_once(&pred, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

/**
 *  得到默认账户
 */
- (TTAccount *)defaultAccount {
    
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:AccountUserIdKey];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    TTAccount *account = [unarchiver decodeObjectForKey:AccountUserIdKey];
    [unarchiver finishDecoding];
    
    return account;
}

/**
 *  设置默认账户
 *
 *  @param account 账户信息
 */
- (void)setDefaultAccount:(TTAccount *)account
{
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    [archiver encodeObject:account forKey:AccountUserIdKey];
    [archiver finishEncoding];
    
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:AccountUserIdKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/**
 *  退出账户
 *
 *  @param account 账户
 */
- (void)removeAccount {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:AccountUserIdKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
